package com.yanchi.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * 自定义Realm（加密版）
 */
public class MD5CustomRealm extends AuthorizingRealm {

    // 授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        Object principal = principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authenticationInfo = new SimpleAuthorizationInfo();

        if ("yanchi".equals(principal)){
            // 给用户赋予角色（数据库查询）
            authenticationInfo.addRole("admin");
            authenticationInfo.addRole("user");

            // 给用户赋予资源（数据库查询）
            authenticationInfo.addStringPermission("user:create:*");
            authenticationInfo.addStringPermission("user:update:001");
        }

        return authenticationInfo;
    }

    // 认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        // 数据库取出的密码
        String password = "d4261206130ff12ad8ff73e08bd226f6";

        // 数据库取出的盐
        String salt = "Salt-YanChi";

        Object principal =  token.getPrincipal();
        if ("yanchi".equals(principal)){
            // 参数一：数据库中用户账号
            // 参数二：数据库中用户密码
            // 参数三：数据库中的随机盐
            // 参数四：提供当前realm的名字
            return new SimpleAuthenticationInfo(
                    principal,
                    password,
                    ByteSource.Util.bytes(salt),
                    this.getName()
            );
        }
        return null;
    }
}
